import WxRequest from './request'
import { env } from './env'

const instance = new WxRequest({
  baseURL: env.baseURL,
  timeout: 15000
})

instance.interceptors.request = (config) => {
  if (wx.getStorageSync('token')) {
    config.header['token'] = wx.getStorageSync('token')
  }
  return config
}

instance.interceptors.response = async (response) => {
  if (!response.isSuccess) {
    wx.toast('网络异常，请稍后重试~')
    return
  }

  switch (response.data.code) {
    case 200:
      return response.data
    case 208:
      const modalStatus = await wx.modal({
        title: '提示',
        content: '登录授权过期，请重新授权'
      })

      if (modalStatus) {
        wx.clearStorageSync()
        wx.navigateTo({
          url: '/pages/login/login'
        })
      }
      return
    default:
      wx.showToast({
        title: '接口调用失败',
        icon: 'none'
      })
      return Promise.reject(response)
  }
}
export default instance
